import {Component, OnInit, TemplateRef} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FetchService} from '../../../core/net/fetch.service';
import {NzMessageService} from 'ng-zorro-antd';
import * as $ from "jquery";
import {UploadChangeParam, UploadFile} from "ng-zorro-antd/upload";
import {NzModalRef, NzModalService} from "ng-zorro-antd/modal";

@Component({
  selector: 'app-regulations',
  templateUrl: './regulations.component.html',
  styleUrls: ['./regulations.component.scss']
})
export class RegulationsComponent implements OnInit {
  modalTitle: string = '';
  modalShow: boolean = false;
  nzBodyStyle: any = {
    padding: '16px 20px 0'
  };
  uploadUrl = `${(window as any).environment.apiBaseUrl}comm/file/upload`;
  fileList: UploadFile[] = [];
  fileModalTitle = '文件上传';
  fileModalShow = false;
  uploadFileId = '';
  uploadFileName = '';
  searchForm: FormGroup;
  tableData = [];

  // 文件预览
  tplModal: NzModalRef;
  fileSrc = '';
  fileType = '';
  fileId = '';
  fileTypeList = ['pdf', 'png', 'jpg'];

  constructor(private fb: FormBuilder,
              private fetchService: FetchService,
              private modal: NzModalService,
              private message: NzMessageService) {
    this.searchForm = this.fb.group({
      name: ['']
    });
  }

  ngOnInit(): void {
    this.queryInfo();
  }

  queryInfo(): void {
    this.fetchService.post<any>('archives/wrsRegulation/list', {name: this.searchForm.value.name})
      .subscribe(res => {
      this.tableData = res.list;
    });
  }

  openFileUploadModal() {
    this.fileList = [];
    this.fileModalShow = true;
  }

  onFileCancel(): void {
    this.fileModalShow = false;
  }

  onFileConfirm(): void {
    const param = {
      name: this.uploadFileName,
      fileId: this.uploadFileId
    };
    this.fetchService.post<any>('archives/wrsRegulation/add', param).subscribe(res => {
      this.message.success('操作成功');
      this.fileModalShow = false;
      this.queryInfo();
    });
  }

  handleChange({file, fileList}: UploadChangeParam): void {
    const status = file.status;
    this.uploadFileId = '';
    if (status === 'done') {
      this.uploadFileId = file.response.data.id;
      this.uploadFileName = file.response.data.fileName;
    }
  }

  viewFile(file, tplContent: TemplateRef<{}>): void {
    const that = this;
    this.fileType = file.name.split('.')[1];
    this.fileId = file.fileId;
    this.fileSrc = `${(window as any).environment.apiBaseUrl}comm/file/view/${file.fileId}`;

    this.tplModal = this.modal.create({
      nzTitle: '文件预览',
      nzContent: tplContent,
      nzWidth: 1100,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: true,
      nzOnCancel(): void {
        that.destroyModal();
      }
    });
  }

  destroyModal() {
    this.tplModal.destroy();
  }

  onDelete(id): void {

  }
}
